import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

import WorkInfo from '../components/WorkInfo';
import ShareLinkDialog from '../components/ShareLinkDialog';
import CastViewer from '../components/CastViewer';

import * as workAction from '../WorkAction';

@connect(mapStateToProps, buildActionDispatcher)
export default class MyWorkDetailComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.onShare = this.onShare.bind(this);
    this.onShareClosed = this.onShareClosed.bind(this);
  }

  onShare() {
    this.setState({
      displayShareLink: true,
    });
  }

  onShareClosed() {
    this.setState({
      displayShareLink: false,
    });
  }

  componentDidMount() {
    const { params, workAction } = this.props;
    workAction.getMyWorkDetail(params.workId).then((work) => {
      this.setState({
        workInfo: work,
      });
    });
  }

  render() {
    const { workInfo } = this.state;
    return (
      <div id="work-detail">
        <div className="user-avatar">
          {workInfo && workInfo.userImagePath &&
            <img src={workInfo.userImagePath} />
          }
          {workInfo && <span className="name">{workInfo.userName}</span>}
        </div>
        <CastViewer workInfo={workInfo} {...this.props} />
        <WorkInfo
          isMine={true}
          work={workInfo}
          onShare={this.onShare}
          location={this.props.location}
        />
        {workInfo && <ShareLinkDialog link={`${window.location.protocol}//${window.location.host}/work/${workInfo.id}/detail`} display={this.state.displayShareLink} onClosed={this.onShareClosed} />}
      </div>
    );
  }

  static get propTypes() {
    return {
      params: PropTypes.any,
      workAction: PropTypes.any,
      location: PropTypes.any
    }
  }
}


function mapStateToProps(state) {
  const { Root, My } = state;
  const isMobile = Root.isMobile;
  const hasLoggerIn = My.Session.hasLoggerIn || false;
  return { isMobile, hasLoggerIn };
}

function buildActionDispatcher(dispatch) {
  return {
    workAction: bindActionCreators(workAction, dispatch),
  };
}
